package com.fish.anne.webapp.action;

import java.util.List;

import com.fish.anne.model.Member;
import com.fish.anne.service.MemberManager;
import com.fish.anne.webapp.formbean.AutoSearch;
import com.fish.anne.webapp.formbean.MemberSearch;
import com.opensymphony.xwork2.Preparable;

public class MemberAction extends BaseAction implements Preparable {
    private MemberManager memberManager;
    private List<Member> members;
    private Member member;
    private Long  memberId;

    public Long getMemberId() {
		return memberId;
	}

	public void setMembers(List<Member> members) {
		this.members = members;
	}

	public void setMemberManager(MemberManager memberManager) {
        this.memberManager = memberManager;
    }

    public List<Member> getMembers() {
        return members;
    }
    private MemberSearch memberSearch;
    public MemberSearch getMemberSearch() {
		return memberSearch;
	}

	public void setMemberSearch(MemberSearch memberSearch) {
		this.memberSearch = memberSearch;
	}

	/**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String memberId = getRequest().getParameter("member.memberId");
            if (memberId != null && !memberId.equals("")) {
                member = memberManager.get(new Long(memberId));
            }
        }
    }

    public String list() {
    	if(memberSearch==null){
    		memberSearch = new MemberSearch();
		}
		Long count = this.memberManager.getCountOfSearch(memberSearch);
		this.memberSearch.setPageTotalRow(count);		
		//autoSearch.setPageRowPerPage(1);
		memberSearch.setPageCurrentPage(getPageCurrentPage());
		 
        members = memberManager.findBySearch(memberSearch);
        return SUCCESS;
    }

    public void setMemberId(Long  memberId) {
        this. memberId =  memberId;
    }

    public Member getMember() {
        return member;
    }

    public void setMember(Member member) {
        this.member = member;
    }

    public String delete() {
        memberManager.remove(member.getMemberId());
        saveMessage(getText("member.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (memberId != null) {
            member = memberManager.get(memberId);
        } else {
            member = new Member();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (member.getMemberId() == null);

        memberManager.save(member);

        String key = (isNew) ? "member.added" : "member.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}